import type { PlatformElementConfig } from '../../interfaces'
import { getCurrentURL } from '../app'

export const IMAGE_PRIORITY = 3

export const COMMON_PAGE_ELEMENTS: Record<string, PlatformElementConfig> = {
  SHORTCUTS: {
    id: 'shortcuts',
    category: 'base-settings',
    categoryKey: 'category',
    priority: 0,
    selector: '',
    inherit: false,
    styleVar: '--shortcuts',
    edit: false,
  },
  PAGE_THEME: {
    id: 'page-theme',
    category: 'base-settings',
    categoryKey: 'category',
    priority: 1,
    selector: '',
    inherit: false,
    styleVar: '--page-theme',
    edit: false,
  },
  PAGE_LOADING: {
    id: 'page-loading',
    category: 'base-settings',
    categoryKey: 'category',
    priority: 2,
    selector: '',
    inherit: false,
    styleVar: '--page-loading',
    edit: false,
  },
  PAGE_CONTAINER: {
    id: 'page-container',
    category: 'advanced-settings',
    categoryKey: 'category',
    priority: 4,
    selector: '',
    inherit: true,
    styleVar: '--page-container',
    edit: false,
  },
  ARTICLE_IMAGE_CUSTOM: {
    id: 'article-image-custom',
    category: 'base-settings',
    categoryKey: 'category',
    priority: 5,
    selector: 'img',
    inherit: false,
    styleVar: '--page-article-image-custom',
    edit: false,
  },
  ARTICLE_TITLE_CUSTOM: {
    id: 'article-title-custom',
    category: 'base-settings',
    categoryKey: 'category',
    priority: 6,
    selector: '',
    inherit: false,
    styleVar: '--page-article-title-custom',
    edit: false,
    remark: '当文章内容中存在<h1>至<h6>标题时，按层级排序后，\n再对前3级标题应用主题样式',
  },
  PAGE_ELEMENTS: {
    id: 'page-elements',
    category: 'base-settings',
    categoryKey: 'category',
    priority: 6,
    selector: '',
    inherit: false,
    styleVar: '--page-elements',
    edit: false,
  },
}

/**
 * 获取指定元素的选择器（带URL动态检查）
 */
export function getElementSelector(pageElement: Record<string, PlatformElementConfig>, elementId: string, currentUrl: string = getCurrentURL()): string {
  const config = pageElement[elementId as keyof typeof pageElement]

  if (!config) {
    // console.error(`[元素配置] 未找到ID为 ${elementId} 的配置`)
    return ''
  }

  // 动态检查是否属于当前页面
  if (config.isCurrentPage && !config.isCurrentPage(currentUrl)) {
    // console.error(`[元素配置] ${elementId} 不属于当前页面 ${currentUrl}`)
    return ''
  }

  return config.selector?.trim() || ''
}
